package com.zhuiYun.project.api.commoditydetail.service.impl;

import com.zhuiYun.project.api.commoditycollection.mapper.CommodityCollectionMapper;
import com.zhuiYun.project.api.commoditydetail.entity.Commodity;
import com.zhuiYun.project.api.commoditycomment.entity.CommodityComment;
import com.zhuiYun.project.api.commoditydetail.entity.CommoditySpec;
import com.zhuiYun.project.api.commoditydetail.entity.UserHistory;
import com.zhuiYun.project.api.commoditycomment.mapper.CommodityCommentMapper;
import com.zhuiYun.project.api.commoditydetail.mapper.CommodityMapper;
import com.zhuiYun.project.api.commoditydetail.mapper.CommoditySpecMapper;
import com.zhuiYun.project.api.commoditydetail.service.CommodityDetailService;
import com.zhuiYun.project.api.handworkdiy.entity.HandworkDiy;
import com.zhuiYun.project.api.handworkdiy.mapper.HandworkDiyMapper;
import com.zhuiYun.project.api.userAddress.entiy.UserAddress;
import com.zhuiYun.project.api.userAddress.mapper.UserAddressMapper;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.util.ObjectUtils;
import com.zhuiYun.project.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName CommodityDetailServiceImpl
 * @Description TODO 商品详情业务层实现类
 * @Author 赵笛
 * @Date 2023/4/4 15:59
 **/
@Service
public class CommodityDetailServiceImpl implements CommodityDetailService {
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    CommoditySpecMapper commoditySpecMapper;
    @Autowired
    CommodityCommentMapper commodityCommentMapper;
    @Autowired
    UserAddressMapper userAddressMapper;
    @Autowired
    CommodityCollectionMapper commodityCollectionMapper;
    @Autowired
    HandworkDiyMapper handworkDiyMapper;


    /**
     * @Author 赵笛
     * @Description TODO 根据id查询当前商品
     * @Date 2023/4/4 16:45
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param commodityId
     */
    @Override
    public CommonResult getCommodityById(Integer commodityId) {
        Commodity commodity = commodityMapper.selectByPrimaryKey(commodityId);
        if(ObjectUtils.isNotEmpty(commodityId)){
            if(ObjectUtils.isNotEmpty(commodity)){
                return CommonResult.ok(commodity);
            }else {
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }

    /**
     * @Author 赵笛
     * @Description TODO 根据商品id查询当前商品规格
     * @Date 2023/4/5 8:59
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param commodityId
     */
    @Override
    public CommonResult getCommoditySpecById(Integer commodityId) {
        List<CommoditySpec> list=commoditySpecMapper.getCommoditySpecById(commodityId);
        if(ObjectUtils.isNotEmpty(commodityId)){
            if(ObjectUtils.isNotEmpty(list)){
                return CommonResult.ok(list);
            }else {
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }

    /**
     * @Author 赵笛
     * @Description TODO getCommentByCommodityId
     * @Date 2023/4/5 12:46
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param commodityId
     */
    @Override
    public CommonResult getCommentByCommodityId(Integer commodityId) {
        List<CommodityComment> list=commodityCommentMapper.getCommentByCommodityId(commodityId);
        if(ObjectUtils.isNotEmpty(commodityId)){
            if(ObjectUtils.isNotEmpty(list)){
                return CommonResult.ok(list);
            }else {
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }

    /**
    * @Description 根据商品ids获取商品信息列表
    * @Author lzy
    * @Date 2023/4/5 19:57
    * @Return com.zhuiYun.project.common.response.CommonResult
    * @param ids
    */
    @Override
    public CommonResult getCommodityListByIds(String ids) {
        String[] commodityIds = ids.split(",");
        Example example = new Example(Commodity.class);
        Example.Criteria criteria = example.createCriteria();
        for (String commodityId : commodityIds) {
            criteria.orEqualTo("id", commodityId);
        }
        criteria.andEqualTo("delFlag", "0");
        List<Commodity> commodities = commodityMapper.selectByExample(example);
        ArrayList<String> commodityIdList = new ArrayList<>(Arrays.asList(commodityIds));
        List<Commodity> commodityListCheckSeckill = commodityMapper.getCommodityListCheckSeckill(commodityIdList);
        /*for (CommodityOrderDTO commodityOrderDTO : commodityListCheckSeckill) {
            boolean equals = commodityOrderDTO.getFavorablePrice().equals("");
            if (!commodityOrderDTO.getSeckillPrice().equals("") && commodityOrderDTO.getSeckillPrice() != null) {
                commodityOrderDTO.setFavorablePrice(commodityOrderDTO.getSeckillPrice());
            }
        }*/
        return CommonResult.ok(commodityListCheckSeckill);
    }
    /**
    * @Author sgo
    * @Description 订单根据Id查询diy商品
    * @Date 2023/4/13 15:30
    * @Return com.zhuiYun.project.common.response.CommonResult
    * @param ids
    */
    @Override
    public CommonResult getCommodDIYityListByIds(String ids) {
        String[] commodityIds = ids.split(",");
        Example example = new Example(HandworkDiy.class);
        Example.Criteria criteria = example.createCriteria();
        for (String commodityId : commodityIds) {
            criteria.orEqualTo("id", commodityId);
        }
        criteria.andEqualTo("delFlag", "0");
        List<HandworkDiy> commodities = handworkDiyMapper.selectByExample(example);
//        ArrayList<String> commodityIdList = new ArrayList<>(Arrays.asList(commodityIds));
//        List<Commodity> commodityListCheckSeckill = commodityMapper.getCommodityListCheckSeckill(commodityIdList);
        /*for (CommodityOrderDTO commodityOrderDTO : commodityListCheckSeckill) {
            boolean equals = commodityOrderDTO.getFavorablePrice().equals("");
            if (!commodityOrderDTO.getSeckillPrice().equals("") && commodityOrderDTO.getSeckillPrice() != null) {
                commodityOrderDTO.setFavorablePrice(commodityOrderDTO.getSeckillPrice());
            }
        }*/
        return CommonResult.ok(commodities);
    }

    /**
     * @Author 赵笛
     * @Description TODO 根据用户id查询收货地址
     * @Date 2023/4/6 11:09
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userId
     */
    @Override
    public CommonResult getAddressList(Integer userId) {
        List<UserAddress> list =userAddressMapper.getAddressList(userId);
        if(ObjectUtils.isNotEmpty(userId)){
            if(ObjectUtils.isNotEmpty(list)){
                return CommonResult.ok(list);
            }else {
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }
    /**
     * @Author 赵笛
     * @Description TODO
     * @Date 2023/4/6 16:03
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param id
     */
    @Override
    public CommonResult getAddressById(Integer id) {
        UserAddress userAddress=userAddressMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isNotEmpty(id)){
            if(ObjectUtils.isNotEmpty(userAddress)){
                return CommonResult.ok(userAddress);
            }else {
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }
    /**
     * @Author 赵笛
     * @Description TODO 根据用户id查询当前用户收藏的商品列表
     * @Date 2023/4/11 14:06
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userId
     * @param commodityName
     */
    @Override
    public CommonResult getCommodityCollectionListByUserId(Integer userId, String commodityName) {
        //校验一下用户id是否为空
        if(ObjectUtils.isNotEmpty(userId)){
            //不为空
            List<Commodity> commodityList = commodityMapper.getCommodityListByIds(userId,commodityName);
            if(ObjectUtils.isNotEmpty(commodityList)){
                //查询结果存在
                return CommonResult.ok(commodityList);
            }else{
                //查询结果为空
                return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
            }
        }else{
            //为空
            return CommonResult.error(EmErrorCode.ID_NULL);
        }

    }
    /**
     * @Author 赵笛
     * @Description TODO 保存用户浏览历史
     * @Date 2023/4/11 19:09
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userHistory
     */
    @Override
    public CommonResult saveUserHistory(UserHistory userHistory) {
        //判断是商品还是diy
        String key ;
        if(userHistory.getItemType()==0){
            key = "commodityHistory"+userHistory.getUserId();
        }else{
            key = "diyHistory"+userHistory.getUserId();
        }
        try {
            //将类型+用户id作为key 商品/diy id作为值存入redis的list当中
            RedisUtil.lSet(key,userHistory.getItemId());
            //为了保证浏览商品的 唯一性,每次添加前,将list 中该商品ID去掉,在加入,以保证其浏览的最新的商品在最前面
            long l = RedisUtil.lRemove(key, 10, userHistory.getItemId());
            //将value push 到该key下的list中,并设置过期时间为一个月
            RedisUtil.lSet(key,userHistory.getItemId(),60*60*24*30);
            //使用ltrim将60个数据之后的数据剪切掉
            //暂时没写
            //历史记录保存成功
            return CommonResult.ok(EmErrorCode.SAVE_OK);
        } catch (Exception e) {
            e.printStackTrace();
            //历史记录保存失败
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }
    /**
     * @Author 赵笛
     * @Description TODO 根据当前用户查找浏览记录
     * @Date 2023/4/11 14:06
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userId
     * @param itemType
     */
    @Override
    public CommonResult getUserHistoryByUserId(Integer userId, Integer itemType) {
        //判断参数是否为空
        if(ObjectUtils.isNotEmpty(userId)&&ObjectUtils.isNotEmpty(itemType)){
            //不为空
            //判断是商品还是diy
            String key;
            if(itemType == 0){
                //是商品
                key = "commodityHistory"+userId;
                List<Object> commodityIdList = RedisUtil.lGet(key,0,-1);
                List<Commodity> commodityList = new ArrayList<>();
                for (Object commodityId :commodityIdList) {
                    Commodity commodity = commodityMapper.getCommodityById((Integer) commodityId);
                    //不为空才执行加入到list中操作
                    if(ObjectUtils.isNotEmpty(commodity)){
                        commodityList.add(commodity);
                    }
                }
                //校验查询的数据是否为空
                if(ObjectUtils.isNotEmpty(commodityList)){
                    //不为空，查询成功
                    return CommonResult.ok(commodityList);
                }else{
                    //为空，查询失败
                    return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
                }
            }else{
                //是diy
                key = "diyHistory"+userId;
                List<Object> diyIdList = RedisUtil.lGet(key,0,-1);
                List<HandworkDiy> diyList = new ArrayList<>();
                for (Object diyId :diyIdList) {
                    HandworkDiy handworkDiy = handworkDiyMapper.getHandworkDiyById((Integer) diyId);
                    //不为空才执行加入到list中操作
                    if(ObjectUtils.isNotEmpty(handworkDiy)){
                        diyList.add(handworkDiy);
                    }
                }
                //校验查询的数据是否为空
                if(ObjectUtils.isNotEmpty(diyList)){
                    //不为空，查询成功
                    return CommonResult.ok(diyList);
                }else{
                    //为空，查询失败
                    return CommonResult.error(EmErrorCode.ID_NOT_OBJECT);
                }
            }
        }else{
            //为空
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }
    /**
     * @Author 赵笛
     * @Description TODO 删除历史记录
     * @Date 2023/4/18 9:56
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param commodityId
     * @param userId
     * @param itemType
     */
    @Override
    public CommonResult deleteHistory(Integer commodityId, Integer userId, Integer itemType) {
        //判断商品/用户id是否存在
        if(ObjectUtils.isNotEmpty(commodityId)&&ObjectUtils.isNotEmpty(userId)){
            String key;
            //判断删除的是商品还是diy
            if(itemType.equals(0)){
                //商品，拼接key
                key = "commodityHistory"+userId;
            }else{
                //diy，拼接key
                key = "diyHistory"+userId;
            }
            //删除值为 commodityId 的值
            long l = 0;
            try {
                //删除成功
                l = RedisUtil.lRemove(key, 1, commodityId);
                return CommonResult.ok(EmErrorCode.DELETE_OK);
            } catch (Exception e) {
                //删除失败
                e.printStackTrace();
                return CommonResult.error(EmErrorCode.DELETE_ERROR);
            }
        }else{
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }
}
